"""
压缩图片
"""
import os
import shutil

from PIL import Image


def compress_image(src_path, dst_path):
    """
    图片压缩批处理
    :param src_path:
    :param dst_path:
    :return:
    """
    for filename in os.listdir(src_path):
        # 如果不存在目的目录则创建一个，保持层级结构
        if not os.path.exists(dst_path):
            os.makedirs(dst_path)
        # 拼接完整的文件或文件夹路径
        src_file = os.path.join(src_path, filename)
        dst_file = os.path.join(dst_path, filename)
        print(src_file)
        print(dst_file)

        # 如果是文件就处理
        if os.path.isfile(src_file):
            if src_file.find('@2x') > 0:
                # 打开原图片缩小后保存，可以用if srcFile.endswith(".jpg")或者split，splitext等函数等针对特定文件压缩
                s_img = Image.open(src_file)
                width, height = s_img.size
                print(width, height)
                try:
                    d_img = s_img.resize((int(width / 2), int(height / 2)), Image.ANTIALIAS)  # 设置压缩尺寸和选项，注意尺寸要用括号
                except Exception as err:
                    print(dst_file + " compressed failed")
                    print(err)
                    continue
                d_img.save(dst_file.replace('@2x', ""))  # 也可以用srcFile原路径保存,或者更改后缀保存，save这个函数后面可以加压缩编码选项JPEG之类的
                print(dst_file + " compressed succeeded")
            elif src_file.find('@3x') > 0:
                s_img = Image.open(src_file)
                width, height = s_img.size
                print(width, height)
                try:
                    d_img = s_img.resize((int(width / 3), int(height / 3)), Image.ANTIALIAS)  # 设置压缩尺寸和选项，注意尺寸要用括号
                except Exception as err:
                    print(dst_file + " compressed failed")
                    print(err)
                    continue
                d_img.save(dst_file.replace('@3x', ""))  # 也可以用srcFile原路径保存,或者更改后缀保存，save这个函数后面可以加压缩编码选项JPEG之类的
                print(dst_file + " compressed succeeded")
            elif src_file.endswith('.png'):
                s_img = Image.open(src_file)
                width, height = s_img.size
                print(width, height)
                try:
                    d_img = s_img.convert('P')
                except Exception as err:
                    print(dst_file + " compressed failed")
                    print(err)
                    continue
                d_img.save(dst_file)  # 也可以用srcFile原路径保存,或者更改后缀保存，save这个函数后面可以加压缩编码选项JPEG之类的
                print(dst_file + " compressed succeeded")
            else:
                shutil.copyfile(src_file, dst_file)

        # 如果是文件夹就递归
        if os.path.isdir(src_file):
            compress_image(src_file, dst_file)


if __name__ == '__main__':
    compress_image("./ShapeU.app", "./new_payload")
